<?php

namespace App\Repositories;


use App\Exceptions\BasicException;
use App\Services\Tools\RedisService;

class SpecialUserRepository
{
    public function getUserInfo($userCode)
    {
        $userData = app('model_user_data')->where('user_code', $userCode)->first();
        if (empty($userData)) {
            throw new BasicException(10001, '用户不存在');
        }
        $userInfo = RedisService::getUserBaseInfo($userData->user_id);
        $info['user_id'] = $userData->user_id;
        $info['nickname'] = $userInfo['nickname'] ?? '';
        $info['head_picture'] = $userInfo['head_picture'] ?? '';
        $info['user_name'] = $userAuthInfo['full_name'] ?? '';
        $info['user_id_number'] = $userAuthInfo['id_number'] ?? '';
        $info['app_status'] = $userAuthInfo['app_status'] ?? 0;
        $info['user_code'] = $userCode;
        $info['mobile'] = app('model_user')->where('user_id', $userData->user_id)->value('mobile');
        return $info;
    }

    /**
     * 创建特殊用户
     * @param $params
     * @return bool
     * @throws BasicException
     */
    public function insertSpecialUser($params)
    {
        $userInfo = $this->getUserInfo($params['user_code']);
        $detail = $this->detail($userInfo['user_id']);

        if (empty($detail)){
            $insert = [];
            $insert['user_id'] = $userInfo['user_id'];
            $insert['user_code'] = $userInfo['user_code'];
            $insert['nickname'] = $userInfo['nickname'];
            $insert['mobile'] = $userInfo['mobile'];
            $insert['is_admin'] = 0;
            $isAdmin = app('model_admin')->where('phone_number',$userInfo['mobile'])->first();
            if (!empty($isAdmin)){
                $insert['is_admin'] = 1;
                $insert['admin_name'] = $isAdmin->realname;
            }
            $insert['created_at'] = date('Y-m-d H:i:s');
            $specialId = app('model_special_user')->insertGetId($insert);
        }else{
            $specialId = $detail->id;
        }
        if ($specialId > 0){
            return $this->updateTags($userInfo['user_id'],$params['tags']);
        }
        return true;
    }

    /**
     * 保存永久封禁的用户
     * @param $uid
     * @return mixed
     */
    public function saveSealUser($uid)
    {
        $detail = $this->detail($uid);
        if ($detail){
            return app('model_special_user')->where('user_id',$uid)->update([
                'status'        =>  1,
                'updated_at'    =>  date("Y-m-d H:i:s")
            ]);
        }
        $userInfo = RedisService::getUserBaseInfo($uid);
        if (empty($userInfo)){
            return false;
        }
        $mobile = app('model_user')->where('user_id', $uid)->value('mobile');
        $insert = [];
        $insert['user_id'] = $uid;
        $insert['user_code'] = $userInfo['user_code'];
        $insert['nickname'] = $userInfo['nickname'];
        $insert['mobile'] = $mobile;
        $insert['is_admin'] = 0;
        $isAdmin = app('model_admin')->where('phone_number',$mobile)->first();
        if (!empty($isAdmin)){
            $insert['is_admin'] = 1;
            $insert['admin_name'] = $isAdmin->realname;
        }
        $insert['status'] = 1;
        $insert['created_at'] = date('Y-m-d H:i:s');
        return app('model_special_user')->insert($insert);
    }

    /**
     * 解封时删除用户或用户封禁状态
     * @param $uid int 用户id
     * @return bool
     */
    public function deleteSealUser($uid)
    {
        $detail = $this->detail($uid);
        if (empty($detail)){
            return true;
        }
        // 验证是否有其他标签，没有标签则删除用户
        $hasTags = app('model_special_user_tags')->where('user_id',$uid)->get();
        if ($hasTags->isEmpty()){
            return app('model_special_user')->where('id',$detail->id)->delete();
        }

        // 解除封禁状态
        if ($detail->status == 1){
           return app('model_special_user')->where('user_id',$uid)->update([
                'status'        =>  0,
                'updated_at'    =>  date("Y-m-d H:i:s")
            ]);
        }
        return true;
    }

    public function detail($userId)
    {
        return app('model_special_user')->where('user_id',$userId)->first();
    }
    /**
     * 获取标签名称
     * @param $tagId
     * @return string
     */
    public function getTag($tagId)
    {
        $ids = [];
        $tags = [
            1   =>  '测试',
            2   =>  '巡查',
            3   =>  '带动',
        ];
        if (isset($tags[$tagId])){
            return $tags[$tagId];
        }
        return '';
    }


    /**
     * 更新用户标签
     * @param $uid
     * @param $tags
     * @return bool
     */
    public function updateTags($uid,$tags)
    {
        $tagIds = explode(',',$tags);
        $del = app('model_special_user_tags')->where('user_id',$uid)->delete();
        if ($del !== false){
            $insert = [];
            foreach ($tagIds as $tagId) {
                $temp = [];
                $temp['user_id'] = $uid;
                $temp['tag_id'] = $tagId;
                $temp['tag_name'] = $this->getTag($tagId);
                $temp['created_at'] = date('Y-m-d H:i:s');
                $insert[] = $temp;
            }
            app('model_special_user_tags')->where('user_id',$uid)->insert($insert);
            return true;
        }
        return false;
    }

    public function updateAuths($uid,$auths)
    {

    }

    public function lists($userCode,$mobile,$tag)
    {
        $model = app('model_special_user')->select(
            'ln_special_user.*'
        );
        $tagTable =app('model_special_user_tags')->getTable();
        if (!empty($userCode)){
            $model->where('ln_special_user.user_code',$userCode);
        }
        if (!empty($mobile)){
            $model->where('ln_special_user.mobile',$mobile);
        }
        if (empty($tag)){
            $lists = $model->leftJoin($tagTable,'ln_special_user.user_id', '=',$tagTable. '.user_id')
                ->orderBy('ln_special_user.id','desc')
                ->groupBy('ln_special_user.user_id')
                ->paginate(20);
        }else{
            $model->where('ln_special_user_tags.tag_id',$tag);
            $lists = $model->leftJoin($tagTable,'ln_special_user.user_id', '=',$tagTable. '.user_id')
                ->orderBy('ln_special_user.id','desc')->paginate(20);
        }

        foreach ($lists as $list){
            $tags = app('model_special_user_tags')->where('user_id',$list->user_id)->get()->toArray();
            $list->tags = array_column($tags,'tag_id');
            $list->auths = [1,2];
        }
        return $lists;
    }

    /**
     * 特殊用户统计
     * @return int[]
     */
    public function listStat()
    {
        $lists = app('model_special_user_tags')->get();
        $total = $test = $xun = $dai = 0;
        foreach ($lists as $item){
            switch ($item->tag_id){
                case 1 :
                    $test++;
                    break;
                case 2:
                    $xun++;
                    break;
                case 3:
                    $dai++;
                    break;
            }
        }
        $total = app('model_special_user')->count();
        $feng = app('model_special_user')->where('status',1)->count();
        return [
            'total'     =>  $total,
            'test'      =>  $test,
            'xun'       =>  $xun,
            'dai'       =>  $dai,
            'feng'      =>  $feng,
        ];
    }

    /**
     * 删除用户及标签
     * @param $ids
     * @return bool
     */
    public function delete($ids)
    {
        $uids = explode(',',$ids);
        $del = app('model_special_user')->whereIn('user_id',$uids)->delete();
        if ($del){
            app('model_special_user_tags')->whereIn('user_id',$uids)->delete();
        }
        return true;
    }
}
